package com.suning.sawp.web.controller.model;

import java.security.Principal;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.suning.sawp.constants.ClerkConstants;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.mainpush.StoreManDto;
import com.suning.sawp.dto.storeman.Category;
import com.suning.sawp.intf.model.ModelAnalyseService;
import com.suning.sawp.intf.model.vo.ContributionCompareResponse;
import com.suning.sawp.intf.model.vo.ContributionResponse;
import com.suning.sawp.intf.model.vo.ModelRecommendResponse;
import com.suning.sawp.intf.model.vo.ModelTopResponse;
import com.suning.sawp.intf.model.vo.ModelValidResponse;
import com.suning.sawp.intf.store.StoreInfoService;
import com.suning.sawp.intf.storeman.StoreManService;
import com.suning.sawp.web.controller.DjBaseController;
import com.suning.sawp.web.exception.MyGsonView;

/**
 * 
 * 样机分析接口<br>
 * 〈功能详细描述〉
 *
 * @author 15050519
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/model/analyse")
public class ModelAnalyseController extends DjBaseController {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ModelAnalyseController.class);

    /**
     * 店员服务
     */
    @Autowired
    StoreManService storeManService;

    /**
     * 样机分析服务
     */
    @Autowired
    ModelAnalyseService modelAnalyseService;

    /**
     * 门店服务
     */
    @Autowired
    StoreInfoService storeInfoService;

    /**
     * 查询店长，督导门店销售的品类，品牌贡献率
     *
     * @param principal
     * @param cateCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryContributionOfMonth.do")
    public MyGsonView queryContributionOfMonth(Principal principal, String cateCode) {
        LOGGER.info("queryContributionOfMonth enter, principal={},cateCode={}", principal.getName(), cateCode);
        // 工号
        String staffId = principal.getName();
        // 返回对象
        ReturnMsg<ContributionResponse> returnMsg = new ReturnMsg<ContributionResponse>();
        ContributionResponse resp = null;
        try {
            // 查询店员信息
            StoreManDto storeMan = storeManService.queryStoreManAttachInfo(staffId);
            // 1. 判断店员是店长，还是督导
            if (ClerkConstants.STORE_KEEPER.equals(storeMan.getPositionId())) {
                // 查询店长贡献率
                resp = modelAnalyseService.queryContributionOfMonth(storeMan.getStoreCode(), cateCode);
            } else if (ClerkConstants.SALE_GUIDE.equals(storeMan.getPositionId())
                    && checkCateCode(cateCode, storeMan.getCategories())) {
                // 查询督导品类贡献率
                resp = modelAnalyseService.queryContributionOfMonth(storeMan.getStoreCode(), cateCode);
            }
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error("queryContributionOfMonth error,staffId=" + staffId + ",cateCode=" + cateCode, e);
        }
        returnMsg.setData(resp);
        LOGGER.info("queryContributionOfMonth exit, principal={},cateCode={}", principal.getName(), cateCode);
        return setGsonView(returnMsg);
    }

    /**
     * 查询店长，督导门店销售的品类，品牌有效性分析
     *
     * @param principal
     * @param cateCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryModelValid.do")
    public MyGsonView queryModelValid(Principal principal, String cateCode) {
        LOGGER.info("queryModelValid enter, principal={},cateCode={}", principal.getName(), cateCode);
        // 工号
        String staffId = principal.getName();
        // 返回对象
        ReturnMsg<ModelValidResponse> returnMsg = new ReturnMsg<ModelValidResponse>();
        ModelValidResponse resp = null;
        try {
            // 查询店员信息
            StoreManDto storeMan = storeManService.queryStoreManAttachInfo(staffId);
            // 1. 判断店员是店长，还是督导
            if (ClerkConstants.STORE_KEEPER.equals(storeMan.getPositionId())) {
                // 查询店长有效样机率
                resp = modelAnalyseService.queryModelValid(storeMan.getStoreCode(), cateCode);
            } else if (ClerkConstants.SALE_GUIDE.equals(storeMan.getPositionId())
                    && checkCateCode(cateCode, storeMan.getCategories())) {
                // 查询督导品类有效样机率
                resp = modelAnalyseService.queryModelValid(storeMan.getStoreCode(), cateCode);
            }
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error("queryModelValid error,staffId=" + staffId + ",cateCode=" + cateCode, e);
        }
        returnMsg.setData(resp);
        LOGGER.info("queryModelValid exit, principal={},cateCode={}", principal.getName(), cateCode);
        return setGsonView(returnMsg);
    }

    /**
     * 查询同级别门店间贡献率比较
     *
     * @param principal
     * @param cateCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryContributionCompare.do")
    public MyGsonView queryContributionCompare(Principal principal, String cateCode) {
        LOGGER.info("queryContributionCompare enter, principal={},cateCode={}", principal.getName(), cateCode);
        // 工号
        String staffId = principal.getName();
        // 返回对象
        ReturnMsg<ContributionCompareResponse> returnMsg = new ReturnMsg<ContributionCompareResponse>();
        ContributionCompareResponse resp = null;
        try {
            // 查询店员信息
            StoreManDto storeMan = storeManService.queryStoreManAttachInfo(staffId);
            // 1. 判断店员是店长，还是督导
            if (ClerkConstants.STORE_KEEPER.equals(storeMan.getPositionId())) {
                // 查询店长贡献率
                resp = modelAnalyseService.queryContributionCompare(storeMan.getRegionCode(), storeMan.getStoreLevel(),
                        null, storeMan);
            } else if (ClerkConstants.SALE_GUIDE.equals(storeMan.getPositionId())
                    && checkCateCode(cateCode, storeMan.getCategories())) {
                // 查询督导品类贡献率
                resp = modelAnalyseService.queryContributionCompare(storeMan.getRegionCode(), storeMan.getStoreLevel(),
                        cateCode, storeMan);
            }
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error("queryContributionCompare error,staffId=" + staffId + ",cateCode=" + cateCode, e);
        }
        returnMsg.setData(resp);
        LOGGER.info("queryContributionCompare exit, principal={},cateCode={}", principal.getName(), cateCode);
        return setGsonView(returnMsg);
    }

    /**
     * 查询店长，督导门店销售的商品TOP
     *
     * @param principal
     * @param cateCode
     * @param flag
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryModelTopTwenty.do")
    public MyGsonView queryModelTopTwenty(Principal principal, String cateCode, String flag) {
        LOGGER.info("queryModelTopTwenty enter, principal={},cateCode={}", principal.getName(), cateCode);
        // 工号
        String staffId = principal.getName();
        // 返回对象
        ReturnMsg<ModelTopResponse> returnMsg = new ReturnMsg<ModelTopResponse>();
        ModelTopResponse resp = null;
        try {
            // 升降序标识位
            String tempFlag = flag;
            // 既不是降序，还不是升序，默认降序
            if (!ClerkConstants.TOP_DESC.equals(flag) && !ClerkConstants.TOP_ASC.equals(flag)) {
                tempFlag = ClerkConstants.TOP_DESC;
            }
            // 查询店员信息
            StoreManDto storeMan = storeManService.queryStoreManAttachInfo(staffId);
            // 1. 判断店员是店长，还是督导
            if (ClerkConstants.STORE_KEEPER.equals(storeMan.getPositionId())) {
                // 查询店长贡献率, 店长忽略品类属性
                resp = modelAnalyseService.queryModelTopTwenty(storeMan.getStoreCode(), null, tempFlag);
            } else if (ClerkConstants.SALE_GUIDE.equals(storeMan.getPositionId())
                    && checkCateCode(cateCode, storeMan.getCategories())) {
                // 查询督导品类贡献率
                resp = modelAnalyseService.queryModelTopTwenty(storeMan.getStoreCode(), cateCode, tempFlag);
            }
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error("queryModelTopTwenty error,staffId=" + staffId + ",cateCode=" + cateCode, e);
        }
        returnMsg.setData(resp);
        LOGGER.info("queryModelTopTwenty exit, principal={},cateCode={}", principal.getName(), cateCode);
        return setGsonView(returnMsg);
    }

    /**
     * 查询店长，督导门店样机推荐
     *
     * @param principal
     * @param cateCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryModelRecommend.do")
    public MyGsonView queryModelRecommend(Principal principal, String cateCode) {
        LOGGER.info("queryModelRecommend enter, principal={},cateCode={}", principal.getName(), cateCode);
        // 工号
        String staffId = principal.getName();
        // 返回对象
        ReturnMsg<ModelRecommendResponse> returnMsg = new ReturnMsg<ModelRecommendResponse>();
        ModelRecommendResponse resp = null;
        try {
            // 查询店员信息
            StoreManDto storeMan = storeManService.queryStoreManAttachInfo(staffId);
            // 1. 判断店员是店长，还是督导
            if (ClerkConstants.STORE_KEEPER.equals(storeMan.getPositionId())) {
                // 查询店长贡献率, 店长忽略品类属性
                resp = modelAnalyseService.queryModelRecommend(storeMan.getStoreCode(), null);
            } else if (ClerkConstants.SALE_GUIDE.equals(storeMan.getPositionId())
                    && checkCateCode(cateCode, storeMan.getCategories())) {
                // 查询督导品类贡献率
                resp = modelAnalyseService.queryModelRecommend(storeMan.getStoreCode(), cateCode);
            }
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error("queryModelRecommend error,staffId=" + staffId + ",cateCode=" + cateCode, e);
        }
        returnMsg.setData(resp);
        LOGGER.info("queryModelRecommend exit, principal={},cateCode={}", principal.getName(), cateCode);
        return setGsonView(returnMsg);
    }

    /**
     * 校验品类编码督导是否所属品类
     *
     * @param cateCode
     * @param categories
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private boolean checkCateCode(String cateCode, List<Category> categories) {
        // 判断品类编码是否为空, 品类列表是否为空
        if (StringUtils.isNotBlank(cateCode) && CollectionUtils.isNotEmpty(categories)) {
            for (Category cate : categories) {
                // 判断品类是否匹配
                if (cateCode.equals(cate.getCategoryCode())) {
                    return true;
                }
            }
        }
        return false;
    }

}
